<template>
  <div class="notice-drawer-container">
    <!-- 邮箱图标 -->
    <el-tooltip content="消息通知" effect="dark" placement="bottom">
      <div class="notice-icon right-menu-item hover-effect" @click="openDrawer">
        <SvgIcon icon-class="email" />
        <el-badge v-if="unreadCount > 0" :value="unreadCount" class="notice-badge" />
      </div>
    </el-tooltip>

    <!-- 通知抽屉 -->
    <el-drawer
      title="消息通知"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="500px"
      :before-close="handleClose"
    >
      <div class="notice-drawer-content">
        <!-- 筛选区域 -->
        <div class="filter-section">
          <!-- 消息类型筛选 -->
          <div class="filter-row">
            <div class="filter-label">消息类型：</div>
            <div class="filter-options">
              <el-button
                v-for="type in noticeTypes"
                :key="type.value"
                :type="selectedType === type.value ? 'primary' : 'default'"
                size="small"
                @click="selectedType = type.value"
              >
                {{ type.label }}
              </el-button>
            </div>
          </div>
          
          <!-- 阅读状态筛选 -->
          <div class="filter-row">
            <div class="filter-label">阅读状态：</div>
            <div class="filter-options">
              <el-button
                v-for="status in readStatus"
                :key="status.value"
                :type="selectedStatus === status.value ? 'primary' : 'default'"
                size="small"
                @click="selectedStatus = status.value"
              >
                {{ status.label }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 通知列表 -->
        <div class="notice-list">
          <div v-if="filteredNotices.length === 0" class="empty-notice">
            <el-empty description="暂无通知消息" />
          </div>
          
          <div v-else class="notice-items">
            <div
              v-for="notice in filteredNotices"
              :key="notice.noticeId"
              class="notice-item"
            >
              <div class="notice-header">
                <div class="notice-title">{{ notice.noticeTitle }}</div>
                <el-button
                  type="text"
                  size="small"
                  @click="readNotice(notice)"
                >
                  阅读消息
                </el-button>
              </div>
              
              <div class="notice-details">
                <dl class="detail-list">
                  <dt>消息发布时间：</dt>
                  <dd>{{ parseTime(notice.createTime) }}</dd>
                  
                  <dt>消息发布人：</dt>
                  <dd>{{ notice.createBy }}</dd>
                  
                  <dt>消息类型：</dt>
                  <dd>
                    <el-tag :type="getNoticeTypeTag(notice.noticeType)">
                      {{ getNoticeTypeLabel(notice.noticeType) }}
                    </el-tag>
                  </dd>
                  
                  <dt>当前状态：</dt>
                  <dd>
                    <el-tag :type="getReadStatusTag(notice)">
                      {{ getReadStatusLabel(notice) }}
                    </el-tag>
                  </dd>
                </dl>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 阅读通知模态框 -->
    <el-dialog
      title="通知详情"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleDialogClose"
    >
      <div v-if="currentNotice" class="notice-detail">
        <div class="detail-header">
          <h3>{{ currentNotice.noticeTitle }}</h3>
          <div class="detail-meta">
            <span>发布时间：{{ parseTime(currentNotice.createTime) }}</span>
            <span>发布人：{{ currentNotice.createBy }}</span>
            <span>类型：{{ getNoticeTypeLabel(currentNotice.noticeType) }}</span>
          </div>
        </div>
        
        <div class="detail-content">
          <div v-html="currentNotice.noticeContent"></div>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button v-if="!isNoticeRead(currentNotice)" type="primary" @click="markAsRead">
          标记为已读
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listUserNotices, markNoticeRead, listUnreadNotice } from '@/api/system/notice'
import { parseTime } from '@/utils/ruoyi'
import { mapGetters } from 'vuex'
import SvgIcon from '@/components/SvgIcon'

export default {
  name: 'NoticeDrawer',
  components: {
    SvgIcon
  },
  data() {
    return {
      drawerVisible: false,
      dialogVisible: false,
      notices: [],
      currentNotice: null,
      unreadCount: 0,
      selectedType: 'all',
      selectedStatus: 'all',
      noticeTypes: [
        { label: '全部', value: 'all' },
        { label: '通知', value: '1' },
        { label: '公告', value: '2' }
      ],
      readStatus: [
        { label: '全部', value: 'all' },
        { label: '已读', value: 'read' },
        { label: '未读', value: 'unread' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'id'
    ]),
    filteredNotices() {
      let filtered = this.notices
      
      // 按类型筛选
      if (this.selectedType !== 'all') {
        filtered = filtered.filter(notice => notice.noticeType === this.selectedType)
      }
      
      // 按阅读状态筛选
      if (this.selectedStatus !== 'all') {
        filtered = filtered.filter(notice => {
          const isRead = this.isNoticeRead(notice)
          return this.selectedStatus === 'read' ? isRead : !isRead
        })
      }
      
      return filtered
    }
  },
  mounted() {
    // 组件挂载时加载未读数量
    this.loadUnreadCount()
  },
  methods: {
    parseTime,
    
    // 打开抽屉
    openDrawer() {
      this.drawerVisible = true
      this.loadNotices()
    },
    
    // 关闭抽屉
    handleClose(done) {
      this.drawerVisible = false
      done()
    },
    
    // 加载通知列表
    async loadNotices() {
      try {
        // 获取当前用户相关的通知列表
        const response = await listUserNotices()
        this.notices = response.rows || []
        
        // 获取未读通知列表，用于判断哪些通知已读
        const unreadResponse = await listUnreadNotice()
        const unreadNotices = unreadResponse.rows || []
        const unreadIds = unreadNotices.map(notice => notice.noticeId)
        
        // 标记已读状态
        this.notices.forEach(notice => {
          notice.isRead = !unreadIds.includes(notice.noticeId)
        })
        
        // 计算未读数量
        this.calculateUnreadCount()
      } catch (error) {
        console.error('加载通知列表失败:', error)
        this.$message.error('加载通知列表失败')
      }
    },
    
    // 加载未读数量
    async loadUnreadCount() {
      try {
        const response = await listUnreadNotice()
        this.unreadCount = response.rows ? response.rows.length : 0
      } catch (error) {
        console.error('加载未读数量失败:', error)
        this.unreadCount = 0
      }
    },
    
    // 计算未读数量
    calculateUnreadCount() {
      // 根据已读状态计算未读数量
      this.unreadCount = this.notices.filter(notice => !this.isNoticeRead(notice)).length
    },
    
    // 判断通知是否已读
    isNoticeRead(notice) {
      if (!notice) return false
      // 根据标记的已读状态判断
      return notice.isRead || false
    },
    
    // 获取通知类型标签
    getNoticeTypeLabel(type) {
      const typeMap = {
        '1': '通知',
        '2': '公告'
      }
      return typeMap[type] || '未知'
    },
    
    // 获取通知类型标签样式
    getNoticeTypeTag(type) {
      const tagMap = {
        '1': 'primary',
        '2': 'success'
      }
      return tagMap[type] || 'info'
    },
    
    // 获取阅读状态标签
    getReadStatusLabel(notice) {
      return this.isNoticeRead(notice) ? '已读' : '未读'
    },
    
    // 获取阅读状态标签样式
    getReadStatusTag(notice) {
      return this.isNoticeRead(notice) ? 'success' : 'warning'
    },
    
    // 阅读通知
    readNotice(notice) {
      this.currentNotice = notice
      this.dialogVisible = true
    },
    
    // 关闭对话框
    handleDialogClose(done) {
      this.dialogVisible = false
      this.currentNotice = null
      done()
    },
    
    // 标记为已读
    async markAsRead() {
      if (!this.currentNotice) return
      
      try {
        await markNoticeRead(this.currentNotice.noticeId)
        this.$message.success('已标记为已读')
        this.dialogVisible = false
        
        // 更新当前通知的已读状态
        const notice = this.notices.find(n => n.noticeId === this.currentNotice.noticeId)
        if (notice) {
          notice.isRead = true
        }
        this.currentNotice.isRead = true
        
        // 重新计算未读数量
        this.calculateUnreadCount()
      } catch (error) {
        console.error('标记已读失败:', error)
        this.$message.error('标记已读失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.notice-drawer-container {
  .notice-icon {
    position: relative;
    cursor: pointer;
    display: inline-block;
    padding: 0 8px;
    height: 100%;
    font-size: 18px;
    color: #5a5e66;
    vertical-align: text-bottom;
    
    &:hover {
      background: rgba(0, 0, 0, .025);
    }
    
    .notice-badge {
      position: absolute;
      top: -5px;
      right: -5px;
    }
  }
}

.notice-drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .filter-section {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    
    .filter-row {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .filter-label {
        width: 80px;
        font-size: 14px;
        color: #606266;
      }
      
      .filter-options {
        flex: 1;
        
        .el-button {
          margin-right: 8px;
          
          &:last-child {
            margin-right: 0;
          }
        }
      }
    }
  }
  
  .notice-list {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    
    .empty-notice {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
    }
    
    .notice-items {
      .notice-item {
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        margin-bottom: 16px;
        padding: 16px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .notice-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          
          .notice-title {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
            flex: 1;
            margin-right: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        
        .notice-details {
          .detail-list {
            margin: 0;
            padding: 0;
            
            dt, dd {
              display: inline-block;
              margin: 0;
              padding: 4px 0;
            }
            
            dt {
              width: 100px;
              font-weight: 500;
              color: #606266;
            }
            
            dd {
              color: #303133;
              margin-left: 8px;
            }
          }
        }
      }
    }
  }
}

.notice-detail {
  .detail-header {
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;
    
    h3 {
      margin: 0 0 12px 0;
      font-size: 18px;
      color: #303133;
    }
    
    .detail-meta {
      color: #909399;
      font-size: 14px;
      
      span {
        margin-right: 20px;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
  
  .detail-content {
    line-height: 1.6;
    color: #303133;
    
    ::v-deep {
      img {
        max-width: 100%;
        height: auto;
      }
      
      table {
        border-collapse: collapse;
        width: 100%;
        
        th, td {
          border: 1px solid #e4e7ed;
          padding: 8px;
        }
      }
    }
  }
}
</style>
